package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryMember;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.mapper.MemberMapper;
import com.itheima.pojo.Member;
import com.itheima.pojo.User;
import com.itheima.pojo.Order;
import com.itheima.pojo.Setmeal;
import com.itheima.service.MemberService;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.management.Query;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = MemberService.class)
@Transactional
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberMapper memberMapper;

    @Override
    public Member findByTelephone(String telephone) {
        return memberMapper.findByTelephone(telephone);
    }


    //添加用户
    public void addMember(Map map) throws ParseException {
        Member member = new Member();
        String birth = resloveNull(map.get("birthday"));
        Date birthday = null;
        if(birth != null){
            birthday = new SimpleDateFormat("yyyy-MM-dd").parse(birth);
        }
        Date regTime = new Date();
        member.setRegTime(regTime);
        member.setBirthday(birthday);
        member.setFileNumber(resloveNull(map.get("fileNumber")));
        member.setIdCard(resloveNull(map.get("idCard")));
        member.setName(resloveNull(map.get("name")));
        member.setPhoneNumber(resloveNull(map.get("phoneNumber")));
        member.setRemark(resloveNull(map.get("remark")));
        member.setSex(resloveNull(map.get("sex")));
        Integer integer = map.get("uid") == null ? null : (Integer) map.get("uid");
        Integer uid = null;
        if(integer != null){
            uid = Integer.valueOf(integer);
        }
        memberMapper.add(member);
        Integer mid = member.getId();
        Map<String,Integer> map1 = new HashMap<>();
        map1.put("user_id",uid);
        map1.put("member_id",mid);
        memberMapper.addMAUId(map1);
    }

    private String resloveNull(Object obj) {
        return obj == null ? null : (String) obj;
    }


    @Override
    public List<Integer> findMemberCountByMonths(List<String> months) {
        List<Integer> memberCount = new ArrayList<>();
        for (String month : months) {
            String date = month + ".31";
            Integer count = memberMapper.findMemberCountBeforeDate(date);
            memberCount.add(count);
        }
        return memberCount;
    }

    @Override
    public Result findByAge() {
        int prson1 = 0, prson2 = 0, prson3 = 0, prson4 = 0, prson5 = 0, prson6 = 0;  //用来计数
        //查询所有会员的年龄
        Integer[]  age1= memberMapper.findAge();

        //遍历  计数
        for (Integer age : age1) {
            if (age!=null) {
                //判断年龄属于哪个阶段
                if (age > 69) prson6++;    //老年
                else if (age >= 46) prson5++;   //中年
                else if (age >= 18) prson4++;        //青年
                else if (age >= 13) prson3++;        //青少年
                else if (age >= 7) prson2++;     //少儿
                else if (age >= 0) prson1++;  //'婴幼儿'
            }
        }

        ArrayList<String> category = new ArrayList<>();
        category.add("婴幼儿");
        category.add("少儿");
        category.add("青少年");
        category.add("青年");
        category.add("中年");
        category.add("老年");

        ArrayList<Object> value = new ArrayList<>();
        value.add(prson1);
        value.add(prson2);
        value.add(prson3);
        value.add(prson4);
        value.add(prson5);
        value.add(prson6);

        HashMap<String, Object> map = new HashMap<>();
        map.put("category",category);
        map.put("value",value);

        return new Result(true,"查询成功",map);

    }
    public List<User> findAllUser() {
        List<User> user = memberMapper.findAllUser();
        return user;
    }

    @Override
    public void edit(Map map) throws ParseException {
        Member member = new Member();
        String birth = resloveNull(map.get("birthday"));
        Date birthday = null;
        if(birth != null){
            birthday = new SimpleDateFormat("yyyy-MM-dd").parse(birth);
        }
        member.setId(map.get("id") == null ? null : (Integer)map.get("id"));
        member.setBirthday(birthday);
        member.setFileNumber(resloveNull(map.get("fileNumber")));
        member.setIdCard(resloveNull(map.get("idCard")));
        member.setName(resloveNull(map.get("name")));
        member.setPhoneNumber(resloveNull(map.get("phoneNumber")));
        member.setRemark(resloveNull(map.get("remark")));
        member.setSex(resloveNull(map.get("sex")));
        Integer integer = map.get("uname") == null ? null : (Integer) map.get("uname");
        Integer uid = null;
        if(integer != null){
            uid = Integer.valueOf(integer);
        }
        memberMapper.edit(member);
        Integer mid = member.getId();
        Map<String, Integer> map1 = new HashMap<>();
        map1.put("user_id", uid);
        map1.put("member_id", mid);
        memberMapper.editMU(map1);
    }

    @Override
    public void add(Member member) {
        memberMapper.add(member);
    }

    @Override
    public void editMember(Member member) {
        memberMapper.edit(member);
    }


    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //分页插件

        PageHelper.startPage(currentPage,pageSize);
        Page<Member> page = memberMapper.selectByCondition(queryString);
        List<Member> members = page.getResult();
        for (Member member : members) {
            User user = memberMapper.findMemberAndUser(member.getId());
            member.setUser(user);
        }
        return new PageResult(page.getTotal(),members);

    }

    public User findById(Integer id) {
        Integer uid = memberMapper.findId(id);
        User user = memberMapper.findByUid(uid);
        return user;
    }

    /**
     * 删除指定角色,如存在关联表则不可删除,并进行提示
     *
     * @param id
     */
    @Override
    public Result deleteById(Integer id) {

        //查询用户关联的订单
        Integer orderNum = memberMapper.findOrderId(id);
            StringBuffer sb = new StringBuffer();
        if (orderNum > 0) {
                sb.append("该角色关联了"+orderNum+"个订单,");
            }
        if ( orderNum > 0 ) {
                //存在关联表,不能删除,并返回关联信息
                sb.append("无法删除该角色");
                return new Result(false, sb.toString());
            }else {
            Integer rNum = memberMapper.findMNum(id);
            if(rNum == 0){
                memberMapper.deleteUserById(id);
            }else {
                memberMapper.deleteUM(id);
                memberMapper.deleteUserById(id);

            }
            //不存在关联表,直接删除角色
            return new Result(true, "删除角色成功");
        }
    }

    /**
     * 批量删除
     * @param ids
     */
    public String delete(Integer[] ids){
        List<Integer> nDUserId = new ArrayList<>();
        List<Integer> iDUserId = new ArrayList<>();
        StringBuffer sb = new StringBuffer();
        for (Integer id : ids) {
            Integer orderNum = memberMapper.findOrderId(id);
            if(orderNum != 0){
                nDUserId.add(id);
            }else {
                iDUserId.add(id);
                Integer rNum = memberMapper.findMNum(id);
                if(rNum == 0){
                    memberMapper.deleteUserById(id);
                }else {
                    memberMapper.deleteUM(id);
                    memberMapper.deleteUserById(id);
                }
            }
        }

        if(nDUserId.size()>0){
            sb.append("id为"+nDUserId+"的用户关联了订单，无法删除该角色，失败删除"+nDUserId.size()+"个用户");
        }
        if(iDUserId.size()>0){
            sb.append("删除id为"+iDUserId+"的用户，成功删除"+iDUserId.size()+"个用户");
        }
        String result = sb.toString();
        return result;
    }

    /**
     * 查询指定期间用户的历史预约记录
     *
     * @param orderInfo
     * @return
     */
    @Override
    public Result findSetmealByIdAndDate(String telephone, Map<String, String> orderInfo) throws Exception {
        try{Member member = findByTelephone(telephone);
            String startDate = (String) orderInfo.get("startDate");
            String endDate = (String) orderInfo.get("endDate");

            Map<String, String> map = new HashMap<>();
            map.put("id", String.valueOf(member.getId()));
            map.put("startDate", startDate);
            map.put("endDate", endDate);

            //返回的封装信息
            List<QueryMember> queryMember = memberMapper.findSetmealByIdAndDate(map);

            return new Result(true, "查询成功", queryMember);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"查询失败");
        }
    }

    /**
     * 根据套餐id查询其预约的具体套餐信息
     *
     * @param id
     * @return
     */
    @Override
    public QueryMember findMemberById(Integer id,Integer oid) {
        Map map=new HashMap();
        map.put("id",id);
        map.put("oid",oid);
        return memberMapper.findMemberById(map);
    }


}
